package com.gzr.server.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.gzr.mapper.ArticleMapper;
import com.gzr.pojo.Article;
import com.gzr.pojo.PageBean;
import com.gzr.server.ArticleServer;
import com.gzr.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServerImpl implements ArticleServer {

    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public void add(Article article) {
        //获取用户id
        Map<String, Object> map = ThreadLocalUtil.get();
        int userId = (int) map.get("id");
        article.setCreateUser(userId);
        article.setCreateTime(new Date());
        article.setUpdateTime(new Date());
        articleMapper.add(article);
    }

    @Override
    public PageBean<Article> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
        //1.创建PageBean对象
        PageBean<Article> pageBean = new PageBean<>();

        //2.开启分页查询 PageHelper
        PageHelper.startPage(pageNum,pageSize);

        //获取用户id
        Map<String, Object> map = ThreadLocalUtil.get();
        int userId = (int) map.get("id");

        List<Article> resultList = articleMapper.list(userId,categoryId,state);
        //Page中提供了方法,可以获取PageHelper分页查询后 得到的总记录条数和当前页数据
        Page<Article> pageArticle = (Page<Article>) resultList;

        //把数据填充到PageBean对象中
        pageBean.setTotal(pageArticle.getTotal());
        pageBean.setItems(pageArticle.getResult());
        return pageBean;
    }

    @Override
    public Article findById(Integer id) {
        //获取用户id
        Map<String, Object> map = ThreadLocalUtil.get();
        int userId = (int) map.get("id");
        return articleMapper.findById(userId,id);
    }

    @Override
    public void update(Article article) {
        article.setUpdateTime(new Date());
        articleMapper.update(article);
    }

    @Override
    public void delete(Integer id) {
        articleMapper.delete(id);
    }
}
